var util = require('../../utils/util.js');
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
Page({
  data: {
    bl0: true, //分享到朋友圈
    statusBarHeight: 0, //胶囊按钮高度
    bl_dl: true, //登录状态
    doginfo: {},
    painting: {},
    shareImage: '',
    saveImage: '',
    cityName: '',
    flg: 0,
  },
  onShareAppMessage: function () {
    let slet = this;
    let doginfo = slet.data.doginfo;
    let path = '/pages/fj/fx?id=' + doginfo.id;
    console.log(path);
    wx.request({
      url: getApp().data.apiUrl + '/AddShare.ashx',
      data: {
        dogid: doginfo.id,
        token: getApp().data.SessionKey
      },
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var resdata = JSON.parse(decodeURIComponent(JSON.stringify(res.data)));
        console.log('share:', resdata);
      }
    })
    return {
      // title: getApp().data.sitename,
      title: `【${this.data.cityName.replace('市', '')}寻狗】走丢了一只${doginfo.pz.replace('犬', '')}，希望各位宠友留意一下`,
      imageUrl: this.data.shareImage,
      path: path
    }
  },
  onShareTimeline: function (res) { //分享到朋友圈
    let slet = this;
    let doginfo = slet.data.doginfo;
    return {
      title: `【${this.data.cityName.replace('市', '')}寻狗】走丢了一只${doginfo.pz.replace('犬', '')}，希望各位宠友留意一下`,
      query: 'id=' + doginfo.id, //页面携带参数
      imageUrl: this.data.shareImage,
    }

  },
  reverseMap() {
    let qqmapsdk = new QQMapWX({
      key: getApp().globalData.mapkey
    });
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: this.data.doginfo.latitude,
        longitude: this.data.doginfo.longitude
      },
      success: ({
        result
      }) => {
        console.log("地图搜索结果",result)
        this.setData({
          cityName: result && result.address_component && result.address_component.city
        })
      },
      fail: function (res) {
        console.log("地图结果失败",res);
      },
      complete: function (res) {}
    });
  },
  onLoad: function (options) {
    let slet = this;
    console.log(options.id);
    // var menuButton = wx.getMenuButtonBoundingClientRect();
    if (getApp().globalData.statusBarHeight == 0) {
      let systemInfo = wx.getSystemInfoSync();
      let statusBarHeight = systemInfo.statusBarHeight;
      statusBarHeight = statusBarHeight * 2;
      let sysButton = wx.getMenuButtonBoundingClientRect();
      getApp().globalData.statusBarHeight = sysButton.top * 2;
    }
    let bl_dl = false;
    if (wx.getStorageSync('LoginSessionKey') != '') {
      bl_dl = true;
    }
    slet.setData({
      statusBarHeight: getApp().globalData.statusBarHeight,
      bl_dl: bl_dl
    })
    wx.showLoading({
      title: '加载中',
      mask: true,
    })
    wx.request({
      url: getApp().data.apiUrl + '/GetDogInfo.ashx',
      data: {
        token: wx.getStorageSync('LoginSessionKey'),
        did: options.id,
        code: options.code
      },
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var resdata = JSON.parse(decodeURIComponent(JSON.stringify(res.data)));
        console.log(resdata);
        slet.setData({
          doginfo: resdata
        },()=>{
          slet.shareReady();
          slet.reverseMap()
        })
      
      },
      complete: function () {
        wx.hideLoading();
      }
    })
  },
  shareReady() {
    let painting = {
      width: 500,
      height: 400,
      clear: true,
      views: [{
        type: 'image',
        url: this.data.doginfo.img,
        top: 0,
        left: 0,
        width: 500,
        height: 400
      }, {
        type: 'image',
        url: '/img/share-tit-ico1.png',
        top: 0,
        left: 0,
        width: 416,
        height: 53
      }]
    }
    this.setData({
      shareImage: this.data.doginfo.img,
      painting
    })
  },
  onShow: function () {

  },
  bindShare(e) //分享到朋友圈
  {
    let slet = this;
    slet.setData({
      bl0: false
    })
  },
  closeShare() {
    let slet = this;
    slet.setData({
      bl0: true
    })
  },
  ImgTap: function (e) { // 图片点击事件
    var slet = this;
    let doginfo = slet.data.doginfo;
    var nowImgUrl = e.target.dataset.src;
    console.log(nowImgUrl);
    let imageUrls = [];
    if (doginfo.img != '' && doginfo.imgtype == 0) {
      imageUrls.push(doginfo.img);
    }
    if (doginfo.img1 != '' && doginfo.imgtype1 == 0) {
      imageUrls.push(doginfo.img1);
    }
    if (doginfo.img2 != '' && doginfo.imgtype2 == 0) {
      imageUrls.push(doginfo.img2);
    }
    wx.previewImage({
      current: nowImgUrl,
      urls: imageUrls
    })
  },
  onGotUserInfo: function (e) { //授权回调
    if (e.detail.rawData != undefined) {
      let slet = this;
      getApp().getInfo();
      var encryptedData = e.detail.encryptedData;
      var iv = e.detail.iv;
      wx.login({ //login流程
        success: function (res) { //登录成功
          if (res.code) {
            let WxCode = res.code;
            let WxEncryptedData = encodeURIComponent(encryptedData);
            let WxIv = iv;
            wx.request({
              url: getApp().data.apiUrl + '/Login.ashx',
              data: {
                code: WxCode,
                encryptedData: WxEncryptedData,
                iv: WxIv
              },
              method: 'GET',
              header: {
                'content-type': 'application/json'
              },
              success: function (res) {
                var resdata = JSON.parse(decodeURIComponent(JSON.stringify(res.data)));
                console.log(resdata);
                if (resdata.status == 1) //注册成功/未审核
                {
                  wx.showToast({
                    title: '账号未审核',
                    icon: 'success',
                    duration: 1000
                  })
                } else if (resdata.status == 2) //已注册
                {
                  wx.setStorageSync('LoginSessionKey', resdata.signature);
                  getApp().data.SessionKey = resdata.signature;
                  slet.setData({
                    bl_dl: true
                  })
                }
              }
            })
          }
        },
        fail: function () { //失败
        },
        complete: function () { //完成
        }
      })
    } else {
      wx.showToast({
        title: '不授权无法使用',
        icon: 'success',
        duration: 1000
      })
    }
  },
  toHome(e) //回首页
  {
    wx.reLaunch({
      url: '/pages/index',
    })
  },
  toBlack(e) //返回
  {
    wx.navigateBack({
      delta: 1
    })
  },
  setCanvasData() {
    let info = this.data.doginfo
    const painting = util.getCanvasConfig({
      bg: '/img/posters-dogs.png',
      banner: info.img,
      textA: this.formatText(info.name, 4),
      textB: this.formatText(info.pz, 4),
      textC: this.formatText(info.money, 6),
      phone: info.tel,
      time: info.time,
      ctx: info.des.replace(/[\r\n]/g, ''),
      local: this.formatText(info.add, 15),
      qecode: info.fxm,
      logo: info.userimg,
      name: this.formatText(info.username + '的寻狗启事', 11),
    })
    this.setData({
      painting
    })
  },
  formatText(txt, l) {
    if (typeof txt != 'string') {
      return ''
    }
    let len = 0
    for (let i = 0; i < txt.length; i++) {
      let t = txt.charAt(i)
      let reg = /[\u4E00-\u9FA5]/g;
      if (reg.test(t)) {
        len += 1
      } else {
        len += .5
      }
      if (len == l) {
        if (i === txt.length - 1) {
          return txt.substr(0, i)
        } else {
          return txt.substr(0, i) + '...'
        }
      } else if (len > l) {
        return txt.substr(0, i - 1) + '...'
      }
    }
    return txt
  },
  saveImage() {
    wx.getSetting({
      success: ({
        authSetting
      }) => {
        if (authSetting.writePhotosAlbum) {
          this.saveImgT()
        } else {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => {
              this.saveImgT()
            },
            fail: () => {
              this.openSet()
            }
          })
        }
      }
    })
  },
  openSet() { // 打开设置页
    let _this = this
    wx.showModal({
      title: '提示',
      content: '请先允许保存到相册',
      success: function (res) {
        if (res.confirm) {
          wx.openSetting({
            withSubscriptions: true,
            success(res) {
              if (res.authSetting['scope.writePhotosAlbum']) {
                _this.saveImgT()
              }
            }
          });
        }
      }
    });
  },
  saveImgT() {
    wx.saveImageToPhotosAlbum({
      filePath: this.data.saveImage,
      success(res) {
        console.log('成功')
        wx.showToast({
          title: '图片保存成功',
          icon: 'none'
        })
      }
    })
  },
  eventGetImage(event) {
    wx.hideLoading()
    const {
      tempFilePath,
      errMsg
    } = event.detail
    if (errMsg === 'canvasdrawer:ok') {
      if (this.data.flg === 0) {
        this.setData({
          shareImage: tempFilePath,
          flg: 1
        })
        setTimeout(() => {
          this.setCanvasData()
        }, 100);
      } else if (this.data.flg === 1) {
        this.setData({
          saveImage: tempFilePath,
          flg: 2
        })
      }
    }

  },
})